package com.refusea.train.mapper

import com.refusea.train.domain.entity.ClassGroup
import com.refusea.train.domain.entity.ClassGroupStudent
import org.apache.ibatis.annotations.Delete
import org.apache.ibatis.annotations.Insert
import org.apache.ibatis.annotations.Mapper
import org.apache.ibatis.annotations.Options
import org.apache.ibatis.annotations.Param
import org.apache.ibatis.annotations.Select
import org.apache.ibatis.annotations.Update

@Mapper
interface ClassGroupStudentMapper {

    @Insert("INSERT INTO class_group_student (school_id, class_group_id, student_id) VALUES (#{schoolId}, #{classGroupId}, #{studentId})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    fun insert(classGroupStudent: ClassGroupStudent): Int

    @Delete("DELETE FROM class_group_student WHERE id = #{id}")
    fun delete(id: Int): Int

    @Update("UPDATE class_group_student SET school_id = #{schoolId}, class_group_id = #{classGroupId}, student_id = #{studentId} WHERE id = #{id}")
    fun update(classGroupStudent: ClassGroupStudent): Int

    @Select("SELECT * FROM class_group_student WHERE id = #{id}")
    fun select(id: Int): ClassGroupStudent?

    @Select("SELECT * FROM class_group_student")
    fun list(): List<ClassGroupStudent>

    @Select(
        """
        SELECT student_id FROM class_group_student 
        WHERE school_id = #{schoolId} AND class_group_id = #{classGroupId}
        """
    )
    fun students(@Param("schoolId") schoolId: Int, @Param("classGroupId") classGroupId: Int): List<Int>

    @Insert(
        """<script>
            INSERT INTO class_group_student (school_id, class_group_id, student_id)
            VALUES
            <foreach collection="studentIds" item="sid" separator=",">
                (#{schoolId}, #{id}, #{sid})
            </foreach>
        </script>"""
    )
    fun inserts(classGroup: ClassGroup): Int

    @Delete("DELETE FROM class_group_student WHERE class_group_id = #{classGroupId} AND school_id = #{schoolId}")
    fun deletes(@Param("classGroupId") classGroupId: Int, @Param("schoolId") schoolId: Int): Int


    @Select(
        """
        <script>
        SELECT class_group_id FROM class_group_student 
        WHERE school_id = #{schoolId} AND student_id IN
        <foreach collection="studentIds" item="sid" separator="," open="(" close=")">
            #{sid}
        </foreach>
        </script>
        """
    )
    fun classGroupIds(@Param("schoolId") schoolId: Int, @Param("studentIds") studentIds: Set<Int>): List<Int>

    @Select("select student_id from class_group_student where class_group_id = #{id}")
    fun studentIds(it: Int): List<Int>
}
